/**
 * Created by ChinaHp on 2016/8/28.
 */
'use strict';
import {
    HttpService,
    Toast
} from '../Http';
import * as types from '../constants/ActionTypes';
import dian from '../../src/img/dian.png'
import baba from '../../src/img/bind/baba.png';
import baba1 from '../../src/img/bind/baba1.png';
import ma from '../../src/img/bind/ma.png';
import ma1 from '../../src/img/bind/ma1.png'
import family from '../../src/img/bind/family.png'
import family1 from '../../src/img/bind/family1.png'
import gege from '../../src/img/bind/gege.png'
import gege1 from '../../src/img/bind/gege1.png'
import jiejie from '../../src/img/bind/jiejie.png'
import jiejie1 from '../../src/img/bind/jiejie1.png'
import tr from '../../src/img/bind/tr.png'
import tr1 from '../../src/img/bind/tr1.png'
import shu from '../../src/img/bind/shu.png'
import shu1 from '../../src/img/bind/shu1.png'
import ye from '../../src/img/bind/ye.png'
import ye1 from '../../src/img/bind/ye1.png'
import nai from '../../src/img/bind/nai.png'
import nai1 from '../../src/img/bind/nai1.png'
import wai from '../../src/img/bind/wai.png'
import wai1 from '../../src/img/bind/wai1.png'
import waipo from '../../src/img/bind/waipo.png'
import waipo1 from '../../src/img/bind/waipo1.png'

var list = [{
    img: baba,
    img1: baba1,
    familystatus: '爸爸',
    ds: '此称呼对应为设备按键'
}, {
    img: ma,
    img1: ma1,
    familystatus: '妈妈',
    ds: '此称呼对应为设备按键'
}, {
    img: family,
    img1: family1,
    familystatus: '家庭',
    ds: '此称呼对应为设备按键'
}, {
    img: gege,
    img1: gege1,
    familystatus: '哥哥',
    ds: '此称呼对应为家庭成员'
}, {
    img: jiejie,
    familystatus: '姐姐',
    img1: jiejie1,
    ds: '此称呼对应为家庭成员'
}, {
    img: tr,
    img1: tr1,
    familystatus: '班主任',
    ds: '仅作为添加班主任时使用'
}, {
    img: shu,
    img1: shu1,
    familystatus: '叔叔',
    ds: '此称呼对应为家庭成员'
}, {
    img: ye,
    img1: ye1,
    familystatus: '爷爷',
    ds: '此称呼对应为家庭成员'
}, {
    img: nai,
    img1: nai1,
    familystatus: '奶奶',
    ds: '此称呼对应为家庭成员'
}, {
    img: wai,
    img1: wai1,
    familystatus: '外公',
    ds: '此称呼对应为家庭成员'
}, {
    img: waipo,
    img1: waipo1,
    familystatus: '外婆',
    ds: '此称呼对应为家庭成员'
}];

const dataUser = {
    "users": [{
        "id": 1,
        "name": "小撸1",
        'email': '11@qq.com'
    }, {
        "id": 2,
        "name": "小撸2",
        'email': '22@qq.com'
    }, {
        "id": 3,
        "name": "小撸3",
        'email': '33@qq.com'
    }]
};

function fetchUsers() {
    return dataUser;
}

function get() {

    const dataUser = {
        "token": [{
            "id": 1,
            "name": "2222",
            'email': '333'
        }]
    };
    return dataUser

}

function setUsers(data) {
    return {
        type: types.SET_USER,
        data
    };
}

function getToken(res) {
    return {
        type: types.GET_TOKEN,
        res
    }
}

function GetDeviceList(res) {
    return {
        type: types.GetDeviceList,
        res
    }
}

function GetCurrentPower(res) {
    return {
        type: types.GetCurrentPower,
        res
    }
}

function Change(res) {
    return {
        type: types.Change,
        res
    }
}

function GetCurrentTrack(res) {
    return {
        type: types.GetCurrentTrack,
        res
    }
}

function AddDevice(res) {
    return {
        type: types.AddDevice,
        res
    }
}

function GetGuardians(res) {
    return {
        type: types.GetGuardians,
        res
    }
}

function GetGuardianss(res) {
    return {
        type: types.GetGuardianss,
        res
    }
}

function ChangeDevice(res) {
    return {
        type: types.ChangeDevice,
        res
    }
}

function GetAddr(msg) {
    return {
        type: types.GetAddr,
        msg
    }
}

function isLong(msg) {
    return {
        type: types.isLogin,
        msg
    }
}

function exportMap(res) {
    return {
        type: types.exportMap,
        res
    }
}

export function changeSaveBabyStatus(msg) {
    return (dispatch, getState) => {
        dispatch(A(msg));
    }
}

export function change(res) {
    const data = {
        authstatus: res.authstatus,
        loststatus: res.loststatus,
        babyname: res.babyname,
        babyid: res.babyid,
        jxtBabyId: res.jxtBabyId,
        babytelephone: res.babytelephone,
        deviceid: res.deviceid,
        headimg: res.headimg,
        deviceType: res.deviceType,
        acindex: res.acindex
    };
    return (dispatch, getState) => {
        dispatch(Change(data));
        if (res.deviceType == 3 || !res.deviceid) {
            return;
        }
        dispatch(getCurrentPower(data.babyid));
        dispatch(getCurrentTrack(data.babyid));
    }
}

export function getUsers() {
    return function(dispatch) {
        dispatch(setUsers(fetchUsers()));
    };
}
export function setSnackbar(message) {
    return {
        type: types.SET_SNACKBAR,
        message
    }
}

export function getChecked(msg) {
    return {
        type: types.GetChecked,
        msg
    }
}

export function getSafeRegions1(res) {
    return {
        type: types.GetSafeRegions1,
        res
    }
}

export function GetAuthInfo(msg) {
    return {
        type: types.GetAuthInfo,
        msg
    }
}

export function A(msg) {
    return {
        type: types.aaa,
        msg
    }
}

export function doLogin2(token, userid) {
    return function(dispatch) {
        localStorage.appToken = token;
        localStorage.userid = userid;
        localStorage.is = '0';
        dispatch(getOneBabyid());
    }

}

/**
 * 选取成员关系
 * @returns {Function}
 */
export function getOneBabyid(acindex = 0) {
    if (localStorage.acindex && localStorage.delDevice != 1) {
        acindex = localStorage.acindex
        delete localStorage.acindex
    }
    return function(dispatch) {
        return HttpService.query({
            url: '/app/object/getBabysJxt',
            sync: false,
            data: {
                token: localStorage.appToken
                //weixinclient: 'true'
            },
            success: (res => {
                if (res.code == 10020) {
                    if (acindex > res.data.length)
                        acindex = 0
                    res.data[0].acindex = acindex;
                    localStorage.babylength = res.data.length;
                    localStorage.babyid = res.data[acindex].babyid;
                    localStorage.userid = res.data[acindex].userid;

                    if (localStorage.newlink) { //判断没有智能学生证
                        let account = 0 //智能学生个数
                        let listItem = res.data.map((json, index) => {
                            if (json.deviceType == 2) {
                                if (account == 0) {
                                    res.data[0].acindex = index;
                                }
                                account++;
                            }
                        });
                        if (account == 0) {
                            dispatch(getChecked(true));
                        } else {
                            dispatch(getChecked(false));
                        }
                    } else {
                        if (res.data[acindex].deviceType == 2) {
                            dispatch(getCurrentPower(res.data[acindex].babyid));
                            dispatch(getCurrentTrack(res.data[acindex].babyid))
                        }
                        if (res.data[acindex].familystatus == '家长')
                            dispatch(getA(res.data[acindex].babyid, res.data))
                        dispatch(getChecked(false));
                    }
                    dispatch(GetDeviceList(res.data));
                } else if (res.code == 401) {
                    document.getElementById('totalpeal').style.display = 'block';
                    Toast.toast(res.msg, 0);
                } else if (res.code == 10019) {
                    dispatch(getChecked(true));
                }
            })
        })
    }
}

/**
 * 是否含有家长
 * @param babyid
 * @param data
 * @returns {Function}
 */

function getA(babyid, data) {
    return function(dispatch) {
        return HttpService.query({
            url: '/app/object/getGuardians',
            data: {
                token: localStorage.appToken,
                babyid: babyid,
                weixinclient: 'true'
            },
            success: (res => {

                if (res.code == '10068') {
                    var getGuardiansList = res.data;
                    for (var y in list) {
                        var ab = 'isOpen';
                        var status = 'check';
                        var id = 'guardianid';
                        list[y][status] = false;
                        list[y][id] = '';
                        for (var x in getGuardiansList) {
                            if (getGuardiansList[x].familystatus == list[y].familystatus) {
                                list[y][status] = true;
                                list[y][id] = getGuardiansList[x].guardianid;
                                break;
                            }
                        }
                    }
                    for (var a in getGuardiansList) {
                        if (getGuardiansList[a].familystatus == '家长') {
                            dispatch(GetDeviceList(data));
                            dispatch(A(true));
                            break;
                        } else {
                            dispatch(A(false))
                        }
                    }
                    dispatch(GetGuardians(list))
                }
            })
        })
    }
}

//判断是否认证
export function getAuthInfo(babyphone) {
    return function(dispatch) {
        return HttpService.query({
            url: '/app/user/getAuthInfo',
            data: {
                token: localStorage.appToken,
                devicetelephone: babyphone,
                weixinclient: 'true'
            },
            success: (res => {
                if (res.code == 10158) {
                    dispatch(GetAuthInfo(res.data))
                } else {}
            })
        })
    }
}
//获取设备电量
export function getCurrentPower(babyid) {
    return function(dispatch) {
        if (localStorage.newlink) {
            return;
        }
        return HttpService.query({
            url: '/app/alarm/getCurrentPower',
            sync: false,
            data: {
                token: localStorage.appToken,
                babyid: babyid,
                weixinclient: 'true'
            },
            success: (res => {
                if (res.code == 10011) {
                    dispatch(GetCurrentPower('0'));
                    localStorage.powerValue = '0';
                    //Toast.toast('未获取到学生证电量信息<br/>请检查电量、或是否开机');
                } else {
                    dispatch(GetCurrentPower(res.data.powerValue));
                    localStorage.powerValue = res.data.powerValue;
                }
            })
        })

    }

}

/**
 * 获取监护人
 * @param babyid
 * @returns {Function}
 */
export function getGuardianss(babyid) {
    return function(dispatch) {
        return HttpService.query({
            url: '/app/object/getGuardians',
            data: {
                token: localStorage.appToken,
                babyid: babyid,
                weixinclient: 'true'
            },
            success: (res => {
                if (res.code == '10068') {
                    var checked = false;
                    var getGuardiansList = res.data;
                    for (var y in list) {
                        var ab = 'isOpen';
                        var status = 'check';
                        var id = 'guardianid';
                        list[y][status] = false;
                        list[y][id] = '';
                        for (var x in getGuardiansList) {
                            if (getGuardiansList[x].familystatus == list[y].familystatus) {
                                list[y][status] = true;
                                list[y][id] = getGuardiansList[x].guardianid;
                                break;
                            }
                        }
                    }
                    dispatch(GetGuardianss(list));
                }
            })
        })
    }
}

//获取设备坐标
function getCurrentTrack(babyid) {
    return function(dispatch) {
        console.log('getCurrentTrack');
        if (localStorage.newlink) {
            return;
        }
        return HttpService.query({
            url: '/app/map/getCurrentTrack',
            sync: false,
            data: {
                token: localStorage.appToken,
                babyid: babyid,
                weixinclient: 'true'
            },
            success: (res => {
                if (res.code == 10059) {
                    //Toast.toast('未获取到定位信息')
                    const data = {
                        lng: 0,
                        lat: 0
                    };
                    dispatch(GetCurrentTrack(data));
                    dispatch(init(116.397428, 39.90923));
                } else if (res.code == 10060) {
                    let getTime = new Date(res.data.gpstime.split(' ')[0]);
                    let nowTime = new Date();
                    let tips = getTime.getFullYear() == nowTime.getFullYear() && getTime.getMonth() == nowTime.getMonth() && nowTime.getDate() == getTime.getDate();
                    dispatch(GetCurrentTrack(res.data));
                    dispatch(init(res.data.lng, res.data.lat))
                    dispatch(getAddree(res.data.lng, res.data.lat))
                } else {
                    Toast.toast(res.msg);
                }
            })

        })
    }
}

/**
 * 获取地理
 * @param lng
 * @param lat
 * @returns {Function}
 */
function getAddree(lng, lat) {
    return function(dispatch) {
        var lnglatXY = [lng, lat]; //已知点坐标
        var geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all"
        });
        geocoder.getAddress(lnglatXY, function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
                var address = result.regeocode.formattedAddress; //返回地址描述
                dispatch(GetAddr(address))
            }
        });
    }
}

/**
 * 初始化地图
 * @param lng
 * @param lat
 * @returns {Function}
 */
function init(lng, lat) {
    return function(dispatch) {
        if (sessionStorage.mapinit != 1) {
            setTimeout(() => {
                dispatch(init(lng, lat));
            }, 600)
            return
        }
        var map,
            marker;
        map = new AMap.Map('container', {
            zoom: 15,
            center: [
                lng, lat
            ],
            resizeEnable: true
        });

        dispatch(exportMap(map));
        if (lng == 116.397428 && lat == 39.90923) {
            return;
        }
        marker = new AMap.Marker({
            map: map,
            icon: dian,
            position: [lng, lat]
        });

        marker.setMap(map);

        var circle = new AMap.Circle({
            center: new AMap.LngLat(lng, lat), // 圆心位置
            radius: 200, //半径
            strokeColor: "#00b4ed", //线颜色
            strokeOpacity: 1, //线透明度
            fillColor: "#00b4ed", //填充颜色
            strokeWeight: 1, //线宽
            fillOpacity: 0.2 //填充透明度
        });
        circle.setMap(map);

    }

}

export function scanDevice(component, mdtcode, status) {
    return function(dispatch) {
        let urlData = {
            mdtid: mdtcode,
            weixinclient: 'true'
        };
        let code = 0;
        if (status == 1) { //绑定设备去往
            component.url = '/app/device/bindDeviceWithBaby'
            urlData.token = localStorage.appToken
            urlData.babyid = localStorage.babyid
        } else if (status == 2) { //无设备第一次添加
            component.url = '/app/user/logon2'
            urlData.userid = localStorage.userid
            code = 100073;
        } else { //添加设备
            component.url = '/app/device/scanDevice'
            urlData.token = localStorage.appToken
            if (status == 0) //更换设备
                urlData.module = 'changedevice'
        }
        return HttpService.query({
            url: component.url,
            data: urlData,
            success: (res => {
                if (res.code == 0 && status == 1) {
                    component.context.router.push(`/success/${res.data.endtime}/${res.data.devicetype}`);
                    return;
                }
                if (res.code == 100785 && status == 0) {
                    component.context.router.push(`/ChangeDevice/${res.data.telephone}/${mdtcode}/${res.data.devicetype}`);
                    return;
                }
                if (res.code == 100783 || res.code == 100064) { //没有管理员情况
                    const telephone = res.data.telephone;
                    const mdtid = res.data.mdtid;
                    const devicetype = res.data.devicetype;
                    component.context.router.push(`/Gotoactive/${telephone}/${mdtid}/${code}/${devicetype}/${status}`);
                    return;
                } else if (res.code == 100063 || res.code == 10078) {
                    //管理员验证码激活
                    const admintelephone = res.data.admintelephone;
                    const mdtid = res.data.mdtid;
                    const deviceid = res.data.deviceid;
                    let telephone = res.data.telephone;
                    if (localStorage.userphone)
                        telephone = localStorage.userphone
                    component.context.router.push(`/VerifyText/${admintelephone}/${mdtid}/${deviceid}/${telephone}/${status}`);
                    return;
                } else {
                    Toast.toast(res.msg);
                }
            })
        })
    }
}

export function getSafeRegions(babyid) {
    return function(dispatch) {
        return HttpService.query({
            url: '/app/map/getSafeRegions',
            data: {
                token: localStorage.appToken,
                babyid: babyid,
                pageindex: 1,
                pagesize: 50,
                weixinclient: 'true'
            },
            success: (res => {
                if (res.code == '10048') {
                    dispatch(getSafeRegions1(res.data.safeRegions));
                }
            })
        })
    }
}
